package com.rtdance.client;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.dom.client.Style.Visibility;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class Rtdance implements EntryPoint {
	@Override
	public void onModuleLoad() {
		registerContactCallback();
	}

	public static void sendMail(String name, String contact, String email, String message){
		
		name = isEmpty(name) ? "" : name.toString();
		contact = isEmpty(contact) ? "" : contact.toString();
		email = isEmpty(email) ? "" : email.toString();
		message = isEmpty(message) ? "" : message.toString();
		
		Map<String, String> valueMap = new HashMap<String,String>();
		valueMap.put("name", name);
		valueMap.put("contact", contact);
		valueMap.put("email", email);
		valueMap.put("message", message);
		
		GreetingServiceAsync async = GWT.create(GreetingService.class);
		
		async.greetServer(valueMap, new AsyncCallback<Boolean>() {
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Couldn't send mail");
				hideMask();
			}

			@Override
			public void onSuccess(Boolean result) {
				hideMask();
				
				DOM.getElementById("submitbutton").getStyle().setVisibility(Visibility.HIDDEN);
				
				Element element = DOM.getElementById("confirmation");
				
				if(result != null && result == true){
					element.setInnerHTML("Your message is received. <br/>We will get back to you in 24 hours");
				}
				else{
					element.setInnerHTML("Server is busy, please try after sometime.");
				}
				
				element.getStyle().setVisibility(Visibility.VISIBLE);
			}
		});
	}
	
	protected native static void hideMask() /*-{
		$wnd.hidemask();		
	}-*/;

	public native void registerContactCallback() /*-{
		$wnd.sendcontactmail = $entry(@com.rtdance.client.Rtdance::sendMail(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;));
	}-*/;
	
	static boolean isEmpty(String value){
		return value==null || value.isEmpty() || value.trim().isEmpty();
	}
}
